<template>
  <div style="width:80%;margin:0 auto;padding:20px 0">
    <!--      <el-button type="primary" size="medium  " style="float: right" @click="downloadPurchaseRecordFormHandle" v-hasPermi="['archive:archiveBorrow:download']" v-if="istype != '3'|| istype !='2'">下载资料采购计划及验证记录模板</el-button>-->

    <h2>借阅申请单</h2>
    <!-- <el-card class="box-card" style="width:90%;margin:0px auto;padding-top:20px"> -->
    <el-row class="mb8" ref="refbut" v-if="istype == '1'">
      <el-col :span="24">
        <el-dropdown style="margin: 2% 4%" @command="(command) => handleCommand(command)"
          v-hasPermi="['archive:archiveBorrow:archiveBorrowReceipt:download']">
          <el-button type="primary" plain>
            下载<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="procurementPlanning">资料采购计划及验证记录模板</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-row ref="queryForm">
      <el-col :span="24">
        <el-form ref="form" :model="form" label-width="120px">
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  申请人
                </span>
                <treeselect v-model="form.borrowUser" :options="deptUserOptions" :normalizer="normalizer"
                  noResultsText="暂无数据" placeholder="请选择申请人" :disable-branch-nodes="true"
                  :disabled="istype == '3' || istype == '2'" />
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="borrowDept">
                <span slot="label">
                  <em style="color:red"> * </em>
                  申请部门
                </span>
                <treeselect v-model="form.borrowDept" :options="deptOptions" noResultsText="暂无数据" placeholder="请选择申请部门"
                  :disabled="istype == '3' || istype == '2'" :normalizer="normalizer" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="申请日期" prop="dengJiTime">
                <el-input v-model="form.dengJiTime" readonly class="input-border"
                  :disabled="istype == '3' || istype == '2'" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  借阅天数
                </span>
                <el-select v-model="form.borrowDays" placeholder="请选择" :disabled="istype == '3' || istype == '2'"
                  style="width: 100%">
                  <el-option v-for="dict in dict.type.JYTS" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  利用目的
                </span>
                <el-select v-model="form.yongtu" placeholder="请选择" clearable :disabled="istype == '3' || istype == '2'"
                  style="width: 100%">
                  <el-option v-for="dict in dict.type.LYMD" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="联系方式">
                <el-input v-model="form.phoneNum" type="phone" :rows="3" :max=11
                  :disabled="istype == '3' || istype == '2'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  是否实体
                </span>
                <el-select v-model="form.daType" placeholder="请选择" clearable :disabled="istype == '3' || istype == '2'"
                  style="width: 100%">
                  <el-option key="E" label="电子" value="E" />
                  <el-option key="F" label="实体" value="F" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :xs="24" v-show="form.daType == 'F'">
              <el-form-item label="现场查看" prop="branchCode" v-has-permi="['archive:borrow:OnSiteInspection']">
                <el-switch v-model="form.branchCode" active-value="1" inactive-value="0" active-text="是" inactive-text="否"
                  :disabled="istype == '3' || istype == '2'" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24" v-show="form.daType == 'F'">
              <el-form-item label="" prop="liyongfangshi">
                <span slot="label">
                  <em style="color:red"> * </em>
                  利用方式
                </span>
                <el-radio-group v-model="form.liyongfangshi" :disabled="istype == '3' || istype == '2'">
                  <el-radio :label="'1'">复印件</el-radio>
                  <el-radio :label="'2'">原件</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="11" :xs="24" v-show="form.daType == 'E'">
              <el-form-item label="是否下载" prop="branchCode">
                <el-switch v-model="form.allowDownload" active-value="1" inactive-value="0" active-text="是"
                  inactive-text="否" :disabled="istype == '3'" @change="changeDownload()" />
              </el-form-item>
              <el-form-item label="是否打印">
                <el-switch v-model="form.allowPrint" active-value="1" inactive-value="0" active-text="是" inactive-text="否"
                  :disabled="istype == '3'" @change="changePrint()" />
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24" v-show="form.daType == 'E'">
              <el-form-item label="下载次数">
                <el-input-number v-model="form.downloadNum" type="number" :rows="3" :min="0" :max="10"
                  :disabled="istype == '3' || form.allowDownload == '0'" @change="changeDownload()"></el-input-number>
              </el-form-item>
              <el-form-item label="打印次数">
                <el-input-number v-model="form.printNum" type="number" :rows="3" :min="0" :max="10"
                  :disabled="istype == '3' || form.allowPrint == '0'" @change="changePrint()"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <!--                    <el-row >
                      <el-col :span="11" :xs="24">
                        <el-form-item label="是否打印" prop="branchCode">
                          <el-switch v-model = "form.allowPrint" active-value="1" inactive-value="0" active-text="是" inactive-text="否"  :disabled="istype == '3'" @change="changePrint()"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="11" :xs="24">
                        <el-form-item label="打印次数"  >
                          <el-input-number v-model="form.PrintNum" type="number" :rows="3" :min="0" :max="10"  :disabled="istype == '3'||form.allowPrint=='0'" @change="changePrint()"></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>-->
          <el-row v-has-permi="['archive:borrow:OnSiteInspection']">
            <el-col :span="11" :xs="24">
              <el-form-item label="是否现场查看" prop="branchCode">
                <el-switch v-model="form.branchCode" active-value="1" inactive-value="0" active-text="是" inactive-text="否"
                  :disabled="istype == '3' || istype == '2'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22" :xs="24">
              <el-form-item label="备 注">
                <el-input v-model="form.beizhu" type="textarea" :rows="3"
                  :disabled="istype == '3' || istype == '2'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>
      </el-col>
    </el-row>
    <el-row class="mb8" ref="refbut" style="width:90%;margin:0 auto" :gutter="20">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="delTap" v-if="istype == '1'">移除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-document" @click="queryTap(0)" v-if="istype == '1'"
          v-hasPermi="['archive:archiveBorrowCar:qwjs']">全文检索</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-tickets" @click="queryTap(1)" v-if="istype == '1'"
          v-hasPermi="['archive:archiveBorrowCar:mljs']">目录检索</el-button>
      </el-col>
      <!--          <el-col :span="1.5">-->
      <!--            是否现场查看：-->
      <!--            <el-switch-->
      <!--              v-model = "form.branchCode"-->
      <!--              active-value="1"-->
      <!--              inactive-value="0"-->
      <!--              active-text="是"-->
      <!--              inactive-text="否"-->
      <!--              :disabled="istype == '3'|| istype =='2'"-->
      <!--             />-->
      <!--          </el-col>-->
    </el-row>
    <div class="tableData">
      <el-table :data="tableDataList" @selection-change="handleSelectionChange" border align="center"
        header-align="center" :loading="loading" :row-key="getRowKeys" lazy :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="width: 96%" :height="height">
        <el-table-column type="selection" width="55" align="center" prop="ID" :selectable="checkboxSelect">
        </el-table-column>
        <el-table-column label="审批意见" width="200" align="center" v-if="istype == '3' || istype == '2'" fixed="left">
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.archiveAgreeStatus"
              :disabled="istype == '3' || cloumnApproval || scope.row.archiveAgreeStatusCanEdit == '0'"
              @change="chanageStatus(scope.row)" v-if="scope.row.isChildren != '1'">
              <el-radio :label="'0'">不同意</el-radio>
              <el-radio :label="'1'">同意</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column width="60" align="center" label="操作" v-if="istype == '2'">
          <template slot-scope="scope">
            <el-button class="wenjianannniu" type="text" icon="el-icon-view" plain @click="celldblclick(scope.row)"
              v-hasPermi="['archive:archiveBorrow:archiveBorrowReceipt:detail']" size="mini" title="查看详情"></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="TITLE" label="题名" width="200" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.DA_TYPE == 'x' ? scope.row.XMMC : scope.row.TITLE }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="BORROW_TYPE" label="借阅类型" width="200" align="center" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ scope.row.BORROW_TYPE == 'E' ? '电子文件' : '实体件' }}</span>
                </template>
              </el-table-column>
        <el-table-column prop="DH" label="档号" width="200" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="RQ" label="日期" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <!--<el-table-column prop="BGQX" label="保管期限" width="180" align="center">
          </el-table-column>-->
        <el-table-column prop="BGQX" label="保管期限" width="120" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-for="(i, idx) in dict.type.BGQX" :key="idx">
              {{ scope.row.BGQX == i.value ? i.label : '' }}
            </span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="STJSFJC" label="实体是否借出" width="120" align="center" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-for="(i, idx) in dict.type.STJSFJC" :key="idx">
                    {{ scope.row.STJSFJC == i.value ? i.label : '' }}
                  </span>
                </template>
              </el-table-column>-->
        <el-table-column prop="CREATE_BY" label="创建人" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="ZRZ" label="责任者" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="BZ" label="备注" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <!--<el-table-column prop="DH" label="档号" align="center"></el-table-column>-->
      </el-table>
    </div>


    <el-row style="width:90%;margin-top:20px" ref="queryForm" v-show="isShowInfo">
      <el-col :span="24">
        <el-form ref="form" :model="form" label-width="120px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  审批意见：
                </span>
                <el-radio-group v-model="form.resource" :disabled="istype == '3'"
                  @change="chanageAllStatus(form.resource)">
                  <el-radio :label="1">全部同意</el-radio>
                  <el-radio :label="0">全部不同意</el-radio>
                  <el-radio :label="2">自定义</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="" v-hasPermi="['archive:archiveBorrow:nextAssignee']"
                v-show="isShowApprover && istype != '3'">
                <span slot="label">
                  <em style="color:red"> * </em>
                  下一节点审批人
                </span>
                <treeselect v-model="form.nextAssignee" :options="roleUserOptions" :normalizer="normalizer"
                  noResultsText="暂无数据" placeholder="请选择审批人" :disable-branch-nodes="true" :disabled="istype == '3'" />
              </el-form-item>
              <el-form-item label="" v-hasPermi="['archive:archiveBorrow:completion']" v-show="istype != '3'">
                <el-checkbox v-model="form.endProcess" :disabled="istype == '3'">办结流程</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="批 注：">
                <el-input v-model="form.note" type="textarea" :rows="3" :disabled="istype == '3'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="j_content margin_top">
        <el-button type="primary" size="medium" @click="submitTap" :disabled="istype == '3'">提交</el-button>
        <!--                <el-button size="medium">取消</el-button>-->
      </el-col>
    </el-row>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" module="borrowReceipt" :celldbData="celldbData"
      @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData" module="borrowReceipt"
      @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->

  </div>
</template>
<script>
import { deptTreeNoDateScope, getUserProfile } from "@/api/system/user";
import estimateTableHeight from '@/mixins/estimateTableHeight' //vue项目中element-tabel自动计算高度
import {
  changeAllArchiveState,
  delArchiveFormSave,
  deptUserTree,
  downloadPurchaseRecordForm,
  formDataSave,
  getArchiveInfo,
  getArchiveList,
  getRouterPath,
  getthbytreenodeHeaderList,
  roleUserTree,
  setArchiveProcessStatusByArchiveId,
  setBorrowProcessDownloadStatus,
  setBorrowProcessPrintStatus,
  submit
} from "@/api/archive/archiveBorrow/borrowReceipt.js" //档案整理接口
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import jianDetailsOpen from '@/components/componentsJianDetails/index.vue' //件详情
import juanDetailsOpen from '@/components/componentsJuanDetails/index.vue' //卷详情
import { getInfo } from "@/api/login";
import { getLastIndexOf } from "@/utils";
import { getRouters } from "@/api/menu";

export default {
  archive_Dicts: ['LYMD', 'BGQX', 'JYTS','STJSFJC'], // 利用目的字典项
  props: ["istype", "isShow", "roleUserList",'reBorrow'],// <!--归档申请单 istype="1"   待办 istype="2"  已办istype="3" -->
  mixins: [estimateTableHeight], // 混入方法
  components: { Treeselect, jianDetailsOpen, juanDetailsOpen },
  data() {
    return {
      form: {
      },
      tableDataList: [],//申请单列表
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      getRowKeys(row) {
        console.log(row)
        return row.ID;
      },
      expands: [],
      // 部门树选项
      deptOptions: [],
      cloumnApproval: false,
      // 人员树选项
      deptUserOptions: [],
      roleUserOptions: [],
      dengJiTime: "",
      isShowInfo: false,
      taskId: '',
      height: undefined,
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      chooseNextAssignee: false,
      chooseNextAssigneeByRoleKey: false,

      // 是否出现审批人
      isShowApprover: false
    }
  },
  created() {
    getRouters().then(res => {
      this.routeList = res.data
    })
    this.getConfigKey("NEXT_ASSIGNEE_ROLE_KEY").then(response => {
      if (response.msg == '') {
        this.chooseNextAssignee = false
      } else {
        this.chooseNextAssignee = true
      }
    });
    this.getConfigKey("NEXT_ASSIGNEE_BY_ROLE_KEY").then(response => {
      if (response.msg == 'true') {
        this.chooseNextAssigneeByRoleKey = true
      } else {
        this.chooseNextAssigneeByRoleKey = false
      }
    });
    this.getDeptTreePost(); //归属部门树接口
    this.deptUserTreePost();//获取人员树接口
    if (this.istype == "1") {
      this.getArchiveList(); //申请单列表
      this.getUserProfile();
      this.height = '15vh'
      // 当前登录人
      getInfo().then(res => {
        this.$set(this.form, 'borrowUser', res.user.userId)
        this.$set(this.form, 'borrowDept', res.user.deptId)
      })
    }

    //当前时间
    const date = new Date()
    const year = date.getFullYear()
    const month = ('0' + (date.getMonth() + 1)).slice(-2)
    const day = ('0' + date.getDate()).slice(-2)
    this.form.dengJiTime = year + "-" + month + "-" + day;

    if (this.isShow == "true") {
      this.isShowInfo = true
    } else {
      this.isShowInfo = false
    }
  },
  filters: {
    formattedTime(value) {
      // 格式化日期，你可以使用任何适合你的格式
      const date = new Date(value);
      return date.toLocaleDateString(); // 返回格式化后的日期字符串
    },
  },
  methods: {


    init(val) {
      console.log(val)
      this.taskId = val.id
      this.form = {}
      this.info = val
      this.processId = val.instanceId
      const menuId = this.$route.meta.menuId
      this.tableDataList = []
      this.deptUserTreePost();//获取人员树接口

      if (val.processVariables != null) {
        console.log(123, val.processVariables)
        this.reset()
        this.form.borrowUser = val.processVariables.borrowUser
        this.form.borrowDept = val.processVariables.borrowDept
        if (val.processVariables.dengJiTime != undefined) {
          this.form.dengJiTime = this.processingTime(val.processVariables.dengJiTime * 1);
        }
        //this.form. = val.processVariables.dengJiTime
        this.form.borrowDays = val.processVariables.borrowDays.toString()
        this.form.yongtu = val.processVariables.yongtu
        this.form.beginCreateTime = val.processVariables.beginCreateTime
        this.form.beizhu = val.processVariables.beizhu
        this.form.phoneNum = val.processVariables.phoneNum
        this.form.daType = val.processVariables.daType
        this.form.allowDownload = val.processVariables.allowDownload
        this.form.liyongfangshi = val.processVariables.liyongfangshi
        this.form.downloadNum = val.processVariables.downloadNum
        this.form.allowPrint = val.processVariables.allowPrint
        this.form.printNum = val.processVariables.printNum
        // this.form.branchCode = val.processVariables.branchCode
        this.$set(this.form, 'branchCode', val.processVariables.branchCode)
        console.log(this.form)
      }
      if (val.otherVariables != null) {
        getInfo().then(res => {
          const userName = res.user.userName
          var arr = val.otherVariables.activitList.filter(item => item.assignee == userName)
          if (arr.length > 0) {
            if (arr[0].isAgree.controlValue == '同意') {
              this.$set(this.form, 'resource', 1)
            } else {
              this.$set(this.form, 'resource', 0)
            }
            let agreeFlag = true;
            let notAgreeFlag = true;
            for (let i = 0; i < this.tableDataList.length; i++) {
              agreeFlag = this.tableDataList[i].archiveAgreeStatus == '1' && agreeFlag ? agreeFlag : false;
              notAgreeFlag = this.tableDataList[i].archiveAgreeStatus == '0' && notAgreeFlag ? notAgreeFlag : false;
            }
            let controlVal = agreeFlag ? 1 : notAgreeFlag ? 0 : 2;
            this.$set(this.form, 'resource', controlVal)
            if (arr[0].comment != null || arr[0].comment != undefined) {
              this.$set(this.form, 'note', arr[0].comment.controlValue)
            }
          }
        })
      }
      if (val.archiveVariables.length != 0) {
        this.tableDataList = val.archiveVariables
        let agreeFlag = true;
        let notAgreeFlag = true;
        for (let i = 0; i < val.archiveVariables.length; i++) {
          this.tableDataList[i].hasChildren = true
          //判断每一行数据的archiveAgreeStatus值，如果都是1，则agreeFlag也是1，如果都是0，则agreeFlag也是0，如果有1有0，则agreeFlag为2
          if (this.tableDataList[i].archiveAgreeStatus == '1' && notAgreeFlag) {
            notAgreeFlag = false
          } else if (this.tableDataList[i].archiveAgreeStatus == '0' && agreeFlag) {
            agreeFlag = false
          }
        }
        if (agreeFlag) {
          this.$set(this.form, 'resource', 1)
        } else if (notAgreeFlag) {
          this.$set(this.form, 'resource', 0)
        } else {
          this.$set(this.form, 'resource', 2)
        }
      }
    },

    //目录检索、全文检索

    queryTap(val) {
      if (val == 0) {
        //全文
        this.$router.push({ path: '/archiveBorrow/fullTextSearch' })
      } else {
        //目录
        this.$router.push({ path: '/archiveBorrow/catalogueSearch' })
      }
    },
    reset() {
      this.form = {
        borrowUser: undefined,
        borrowDept: undefined,
        dengJiTime: undefined,
        borrowDays: undefined,
        yongtu: undefined,
        beginCreateTime: undefined,
        beizhu: undefined,
        phoneNum: undefined,
        daType: undefined,
        allowDownload: undefined,
        liyongfangshi: undefined,
        downloadNum: undefined,
        allowPrint: undefined,
        printNum: undefined,
      }
    },
    changeDownload() {
      if (this.istype == '2') {
        let resource = this.form.resource;
        let note = this.form.note;
        let formData = {
          processId: this.processId,
          allowDownload: this.form.allowDownload,
          downloadNum: this.form.downloadNum
        }
        this.info.processVariables.allowDownload = this.form.allowDownload
        this.info.processVariables.downloadNum = this.form.downloadNum
        setBorrowProcessDownloadStatus(formData).then(response => {
          this.init(this.info)
          this.$forceUpdate();
          this.form.resource = resource;
          this.form.note = note;
        });
      }
    },
    changePrint() {
      if (this.istype == '2') {
        let resource = this.form.resource;
        let note = this.form.note;
        let formData = {
          processId: this.processId,
          allowPrint: this.form.allowPrint,
          printNum: this.form.printNum
        }
        this.info.processVariables.allowPrint = this.form.allowPrint
        this.info.processVariables.printNum = this.form.printNum
        setBorrowProcessPrintStatus(formData).then(response => {
          this.init(this.info)
          this.$forceUpdate();
          this.form.resource = resource;
          this.form.note = note;
        });
      }
    },
    getUserProfile() {
      getUserProfile().then(response => {
        this.$set(this.form, 'borrowUser', response.data.userId)
        this.$set(this.form, 'borrowDept', response.data.deptId)
        this.$set(this.form, 'phoneNum', response.data.phonenumber)
      });
    },
    processingTime(time) {
      const date = new Date(time);
      // 获取日期的年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      // 获取时间的小时、分钟、秒
      // const hours = String(date.getHours()).padStart(2, '0');
      // const minutes = String(date.getMinutes()).padStart(2, '0');
      // const seconds = String(date.getSeconds()).padStart(2, '0');
      // 构建日期时间字符串
      return `${year}-${month}-${day}`;
    },
    chanageAllStatus(resource) {
      if (this.chooseNextAssigneeByRoleKey && resource == '1') {
        let agreeUserList = this.roleUserList.agreeUserList
        this.roleUserOptions = agreeUserList
      } else if (this.chooseNextAssigneeByRoleKey && resource == '0') {
        let notAgreeUserList = this.roleUserList.notAgreeUserList
        this.roleUserOptions = notAgreeUserList
      } else if (this.chooseNextAssigneeByRoleKey && resource == '2') {
        let otherUserList = this.roleUserList.otherUserList
        this.roleUserOptions = otherUserList
      }
      if (this.roleUserOptions == undefined || this.roleUserOptions.length == 0) {
        this.isShowApprover = false
      } else {
        this.isShowApprover = true
      }
      if (resource == '0' || resource == '1') {
        /*for (let i = 0; i < this.tableDataList.length; i++) {
          this.tableDataList[i].archiveAgreeStatus = '0';
          this.chanageStatus(this.tableDataList[i],0);
        }*/
        //TODO 新建接口批量修改
        changeAllArchiveState(this.processId, resource).then(resp => {
          this.cloumnApproval = false;
          for (let i = 0; i < this.tableDataList.length; i++) {
            if (this.tableDataList[i].archiveAgreeStatusCanEdit != 0) {
              this.tableDataList[i].archiveAgreeStatus = resource + '';
            }
          }
          //this.init(this.info)
          this.form.resource = resource;
          this.cloumnApproval = true;
          this.$forceUpdate();
        })
      } else if (resource == '2') {
        this.cloumnApproval = false;
        this.form.resource = resource;
        this.$forceUpdate();
      }

    },
    formattedTime(value) {
      // 格式化日期，你可以使用任何适合你的格式
      const date = new Date(value);
      return date.toLocaleDateString(); // 返回格式化后的日期字符串
    },
    handleCommand(command) {
      switch (command) {
        case "procurementPlanning":
          this.downloadPurchaseRecordFormHandle();
          break;
        default:
          break;
      }
    },
    downloadPurchaseRecordFormHandle() {
      downloadPurchaseRecordForm().then((response) => {
        // 创建一个 Blob 对象，用于存储二进制数据

        const blob = new Blob([response], { type: "application/octet-stream" });

        // 创建一个下载链接
        const url = window.URL.createObjectURL(blob);

        // 创建一个 <a> 元素并设置下载链接
        const link = document.createElement('a');
        link.href = url;
        link.download = '资料采购计划及验证记录.docx'; // 设置下载的文件名

        // 模拟点击 <a> 元素来触发下载
        link.click();

        // 释放资源
        window.URL.revokeObjectURL(url);
      })
        .catch((error) => {
          console.error('下载文件时出错：', error);
        });
    },
    /** 查询部门下拉树结构 */
    getDeptTreePost() {
      deptTreeNoDateScope().then(response => {
        this.deptOptions = response.data;
      });
    },

    /**获取人员树接口 */
    deptUserTreePost() {

      deptUserTree().then(response => {
        this.deptUserOptions = response.data;
        if (this.deptUserOptions != undefined) {
          // 重命名树结构中的字段
          this.deptUserOptions.forEach(node => {
            this.appendUser(node);
          });
        }
        // console.log(this.deptUserOptions)
      });
      if (this.istype == '2' && this.chooseNextAssigneeByRoleKey == false) {
        roleUserTree().then(response => {
          this.roleUserOptions = response.data;
          if (this.roleUserOptions != undefined) {
            // 重命名树结构中的字段
            this.roleUserOptions.forEach(node => {
              this.appendUser(node);
            });
            this.isShowApprover = true
          } else {
            this.isShowApprover = false
          }
          // console.log(this.roleUserOptions)
        });
      }
    },
    appendUser(node) {
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.appendUser(child);
        });
      }
      if (node.userChildren && node.userChildren.length > 0) {
        node.userChildren.forEach(user => {
          user.nodeType = 'user'; // 添加 nodeType 属性
        });
        node.children = [...(node.children || []), ...node.userChildren];
        delete node.userChildren;
      }
    },
    normalizer(node) {
      // console.log(node)
      // console.log(node.children,"++111111111111111++")
      if (node.nodeType != 'user') {
        if (node.children == undefined || node.children == null) {
          node["children"] = undefined
          node['isDisabled'] = true;
        }
      }

      if (node.children == null || node.children == undefined || !node.children.length) {
        delete node.children;
      }
      return node
      //去掉children=[]的children属性
      // if (node.children && !node.children.length) {
      //     delete node.children;
      // }
      // if (node.isLeaf == 'Y' && node.typeLevel != 3) {
      //     node['isDisabled'] = true;
      // }
      // return {
      //     id: node.typeId,
      //     label: node.typeName,
      //     children: node.children,
      // }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.onlyEorF = true;
      this.eFile = true;
      this.fFile = true;
      this.isBorrowed = false;
      for (let i = 0; i < selection.length; i++) {
        let item = selection[i]
        console.log(item)
        if (item.BORROW_TYPE == 'E') {
          this.fFile = false;
        }
        if (item.BORROW_TYPE == 'F') {
          this.eFile = false;
          if (item.STJSFJC == 1) {
            this.isBorrowed = true;
          }
        }
      }
      this.onlyEorF = this.eFile || this.fFile;
    },
    getArchiveList() {
      this.loading = true;
      getArchiveList().then(res => {
        this.loading = false;
        const menuId = this.$route.meta.menuId
        if (res.code == "200" && this.istype == "1" && res.data != undefined) {
          this.tableDataList = res.data;
          for (let i = 0; i < res.data.length; i++) {
            this.tableDataList[i].hasChildren = true
          }
        } else if (res.data == undefined) {
          this.tableDataList = [];
        }
      })
    },
    // 懒加载表格数据
    load(tree, treeNode, resolve) {
      console.log(tree, resolve)
      setTimeout(() => {
        var level = "";
        if (getLastIndexOf(tree.SUB_TABLE_NAME) == "F") {  //F 件
          level = 'efile'
        } else if (getLastIndexOf(tree.SUB_TABLE_NAME) == "V") { //卷
          level = 'jian'
        } else { //项目
          level = 'juan'
        }
        const menuId = this.$route.meta.menuId
        const archiveId = tree.ID
        const categoryId = tree.CATEGORY_ID
        if (level != 'efile') {
          getArchiveInfo(
            {
              menuId: menuId, level: level, archiveId: archiveId, categoryId: categoryId
            }
          ).then(response => {
            for (let i = 0; i < response.rows.length; i++) {
              response.rows[i].hasChildren = true
              response.rows[i].isChildren = '1'
            }
            console.log(response.rows)
            resolve(response.rows)
          })
        } else {
          console.log("dklfjlsdkjf")
          resolve([])
        }
      }, 1000)
    },
    // 是否禁用多选框
    checkboxSelect(row) {
      if (row.isChildren == '1') {
        return false
      } else {
        return true
      }
    },
    delTap() {
      // console.log(this.multiple, this.single, ")))")
      if (this.multiple) {
        this.$message({ message: '请选择要移除的数据哦', type: 'warning' })
      } else {
        this.$modal.confirm('是否确认所选数据项？').then(() => {
          delArchiveFormSave(this.ids).then(res => {
            this.$modal.msgSuccess("删除成功");
            this.getArchiveList();
          })


        }).catch(() => { });

      }
    },
    //提交
    submitTap() {
      console.log(this.form,"-----------")
      // 获取人员
      if (this.multiple && this.istype == "1") {
        this.$message({ message: '请选择要提交的数据哦', type: 'warning' })
        return;
      }
      if (!this.onlyEorF && this.istype == "1") {
          this.$message({ message: '请选择一种类型的数据（实体/电子)', type: 'warning' })
          return;
        }
        // console.log((this.form.daType == 'F' && this.eFile) || (this.form.daType == 'E' && this.fFile), this.form.daType, this.fFile, "00000000000000000000000000000")
      const personnel = this.findNodeById(this.form.borrowUser, this.deptUserOptions);
      /*if (personnel) {
        this.form.submitUser = personnel.label
      }*/
      // 获取部门
      const department = this.findNodeById(this.form.borrowDept, this.deptOptions)
      /*if(department) {
        this.form.submitDept = department.label
      }*/
      if (personnel == undefined || personnel == null || personnel == "") {
        this.$modal.msgError("申请人不能为空");
        return;
      } else if (department == undefined || department == null || department == "") {
        this.$modal.msgError("申请部门不能为空");
        return;
      } else if (this.form.borrowDays == undefined || this.form.borrowDays == null || this.form.borrowDays == "") {
        this.$modal.msgError("借阅天数不能为空");
        return;
      } else if (this.form.yongtu == undefined || this.form.yongtu == null || this.form.yongtu == "") {
        this.$modal.msgError("利用目的不能为空");
        return;
      }
      if ((this.form.daType == 'F' && this.eFile) || (this.form.daType == 'E' && this.fFile)) {
        this.$message({ message: '请选择与借阅单相同类型的数据', type: 'warning' })
        return;
      }
      if (this.form.daType == "" || this.form.daType == undefined || this.form.daType == null) {
        this.$modal.msgError("是否实体不能为空");
        return;
      }
      if (this.fFile && (this.form.liyongfangshi == "" || this.form.liyongfangshi == undefined || this.form.liyongfangshi == null)) {
        this.$modal.msgError("利用方式不能为空");
        return;
      }
      if (this.form.daType == 'F' && this.isBorrowed) {
        this.$message({ message: '您选择的档案原件已被借出', type: 'warning' })
        return;
      }
      if (this.chooseNextAssignee && !this.form.endProcess && this.isShowApprover) {
        if (this.form.nextAssignee == undefined || this.form.nextAssignee == null || this.form.nextAssignee == '') {
          this.$modal.msgError("请选择下一审批人");
          return;
        }
      }
      // <!--归档申请单 istype="1"   待办 istype="2"  已办istype="3" -->
      if (this.istype == "1") {
        console.log(this.form)
        this.$modal.confirm('是否确认提交？').then(() => {
          submit(this.form, this.ids).then(res => {
            this.$modal.msgSuccess(res.msg)
            this.getArchiveList()
            // const currentPath = this.$route.path;
            // const parts = currentPath.split('/');
            // const lastPart = parts[parts.length - 1];
            // const jumpAddress = currentPath.replace(lastPart, 'archiveBorrowTask');
            // if (this.hasRoute("archiveBorrowTask")) {
            //   this.$router.push({
            //     path: jumpAddress
            //   });
            // } else {
            //   this.$message({
            //     message: '您还没开通权限哦',
            //     type: 'warning'
            //   });
            // }
            getRouterPath({ path: 'archive/archiveBorrow/archiveBorrowReceipt/notQrocessed/index' }).then(res => {
              if (res.data != undefined) {
                this.$router.push({
                  path: res.data
                });
              } else {
                /*this.$message({
                  message: '您还没开通权限哦',
                  type: 'warning'
                });*/
              }
            })
          })
        }).catch(() => {
        });
      } else if (this.istype == '2') {
        if (this.form.resource == null || this.form.resource == undefined) {
          this.$modal.msgWarning('请选择审批意见')
          return;
        }
        let agreeFlag = true;
        let notAgreeFlag = true;
        let controlVal = 1;
        if (this.form.resource == '2') {
          for (let i = 0; i < this.tableDataList.length; i++) {
            if (this.tableDataList[i].archiveAgreeStatus == undefined || this.tableDataList[i].archiveAgreeStatus == '') {
              this.$modal.msgWarning('请为所有数据选择审批意见')
              return;
            } else {
              agreeFlag = this.tableDataList[i].archiveAgreeStatus == '1' && agreeFlag ? agreeFlag : false;
              notAgreeFlag = this.tableDataList[i].archiveAgreeStatus == '0' && notAgreeFlag ? notAgreeFlag : false;
            }
          }
          controlVal = agreeFlag ? 1 : notAgreeFlag ? 0 : 1;
        } else {
          controlVal = this.form.resource;
        }

        var data = []
        if (this.form.endProcess == true) {
          controlVal = 2;
        }
        data = [{
          controlId: 'is_agree',
          controlDefault: '不同意--__--同意--__--办结',
          controlIsParam: 'i',
          controlLable: '审批意见',
          controlType: 'radio',
          controlValue: controlVal
        }, {
          controlId: "comment",
          controlDefault: 'FormProperty_2ugo1se',
          controlIsParam: 'f--!!null',
          controlLable: '批注',
          controlType: 'textarea',
          controlValue: this.form.note
        }, {
          controlId: "nextAssignee",
          controlDefault: 'FormProperty_298545',
          controlIsParam: 'f--!!null',
          controlLable: '下一节点办理人',
          controlType: 'input',
          controlValue: this.form.nextAssignee
        }];
        data.id = this.taskId
        formDataSave(data).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.$emit('close')
        })
        this.$emit('close')
      }
      // his.getArchiveList();
    },
    findNodeById(id, nodes) {
      for (const node of nodes) {
        if (node.id == id) {
          return node;
        }
        if (node.children) {
          const result = this.findNodeById(id, node.children);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    celldblclick(row) {
      console.log(row, '------------------')
      var label = "";
      var level = "";
      if (getLastIndexOf(row.SUB_TABLE_NAME) == "F") {  //F 件
        level = 0
        label = row.TITLE;
      } else if (getLastIndexOf(row.SUB_TABLE_NAME) == "V") { //卷
        level = 1
        label = row.TITLE;
      } else { //项目
        level = 3
        label = row.XMMC;
      }
      const menuId = this.$route.meta.menuId
      getthbytreenodeHeaderList(
        {
          categoryId: row.CATEGORY_ID, menuId: menuId, subTableName: row.SUB_TABLE_NAME
        }
      ).then(response => {
        var tableHeaderList = response.rows
        this.celldbData = {
          id: row.ID,
          categoryId: row.CATEGORY_ID,
          menuId: menuId,
          sub_table_name: row.SUB_TABLE_NAME,
          label: label,
          level: level,
          ifSub_table_name: row.SUB_TABLE_NAME,
          isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList: tableHeaderList,
          borrowId: this.info.processVariables.borrowId // 借阅单的id
        }
        this.$nextTick(() => {
          if (getLastIndexOf(row.SUB_TABLE_NAME) == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      })
    },
    //隐藏展开箭头
    getRowClass(row) {
      if (row.row.children1 === undefined) {
        return 'row-expand-cover';
      }
      if (row.row.children1.children2 === undefined) {
        return 'row-expand-cover';
      }
    },
    chanageStatus(row) {
      this.form = {
        processId: this.processId,
        archiveId: row.ID,
        status: row.archiveAgreeStatus
      }
      setArchiveProcessStatusByArchiveId(this.form).then(response => {
        this.init(this.info)
        this.flag = true
        this.form.resource = 2;
        this.$forceUpdate();
      })
    },
    hasRoute(path, routeList) {
      !routeList && (routeList = this.routeList, console.log('执行'))
      for (let i = 0; i < routeList.length; i++) {
        if (routeList[i].path == path) {
          // console.log(routeList[i].path, path, "shuju")
          return true
        }
        if (routeList[i].children) {
          let flag = this.hasRoute(path, routeList[i].children)
          // console.log(path, routeList[i].children, "000")
          if (flag) {
            return flag
          }
        }
      }
      return false
    },
  }
}
</script>
<style lang="scss" scoped>
h2 {
  display: block;
  text-align: center;
  line-height: 30px;
  font-size: 30px;
  font-weight: bold;
}

.j_content {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.margin_top {
  margin-top: 20px
}

::v-deep .input-border input {
  border: 0 !important;
}

.tableData {
  overflow-y: auto;
  width: 90%;
  margin: 20px auto 0;
}

.wenjianannniu {
  font-size: 18px;
  margin-left: 2px;
}
</style>
